package com.wujilin.okra.fragment;

import static android.app.Activity.RESULT_OK;
import static android.content.DialogInterface.BUTTON_POSITIVE;
import static com.wujilin.okra.Okra.EXTRA_CATEGORY_ID;
import static com.wujilin.okra.Okra.EXTRA_CATEGORY_NAME;
import static com.wujilin.okra.Okra.T_CATEGORY;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.wujilin.okra.R;
import com.wujilin.okra.database.Sql;

/**
 * 
 * @author Belin Wu
 */
public class CategoryNewFragment extends DialogFragment implements DialogInterface.OnClickListener {
	private EditText categoryEdit;
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_category, null);
		categoryEdit = (EditText) view.findViewById(R.id.category);
		
		Dialog dialog = new AlertDialog.Builder(getActivity())
				.setTitle(R.string.new_category)
				.setView(view)
				.setPositiveButton(android.R.string.ok, this)
				.setNegativeButton(android.R.string.cancel, null)
				.create();
		return dialog;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (which == BUTTON_POSITIVE) {
			String category = categoryEdit.getText().toString();
			long id = Sql.insert(T_CATEGORY, "name", category);
			
			Intent data = new Intent();
			data.putExtra(EXTRA_CATEGORY_ID, id);
			data.putExtra(EXTRA_CATEGORY_NAME, category);
			getTargetFragment().onActivityResult(getTargetRequestCode(), RESULT_OK, data);
		}
	}
}
